﻿/*
 * PSRtpPackager.cpp
 *
 *  Created on: 2015年7月5日
 *      Author: terry
 */

#include "PSRtpPackager.h"
#include "CLog.h"


namespace av
{


PSRtpPackager::PSRtpPackager(bool useMark):
    m_lastPktTime(),
	m_useRtpTime(),
	m_useMark(useMark)
{
}

PSRtpPackager::~PSRtpPackager()
{
}

void PSRtpPackager::slice(const MediaPacket& pkt, int maxSize, RtpPackagerSink* pSink)
{
	if (!pSink)
	{
		return;
	}

	if (pkt.size <= maxSize)
	{
		RtpPacket pktOut;
		pktOut.data = pkt.data;
		pktOut.size = pkt.size;
		pktOut.ts = (uint32_t)pkt.pts;

		pktOut.mark = m_useMark;
		pktOut.pt = m_payload;

		pSink->onSlicePacket(pktOut);
	}
	else
	{
		RtpPacket pktOut;
		pktOut.ts = (uint32_t)pkt.pts;
		pktOut.pt = m_payload;

		uint8_t* p = pkt.data;
		int leftSize = pkt.size;
		while (leftSize > maxSize)
		{
			pktOut.data = p;
			pktOut.size = maxSize;
			pktOut.mark = false;

			p += maxSize;
			leftSize -= maxSize;

			pSink->onSlicePacket(pktOut);
		}

		pktOut.data = p;
		pktOut.size = leftSize;
		pktOut.mark = m_useMark;
		pSink->onSlicePacket(pktOut);

	}
}

bool PSRtpPackager::join(const RtpPacket& pktIn, MediaPacket& pktOut)
{
	//实现PS流到ES流的解析.

	PsParser::Packet parserPkt;
	if (!m_parser.parse(pktIn.data, pktIn.size, parserPkt))
	{
		return false;
	}

	if (!m_parser.getFormat().isValid())
	{
		/// 还没有收到 0xBC
		//CLog::warning("PSRtpPackager parsed. format is not valid.\n");
		return false;
	}

	int64_t pts = m_useRtpTime ? pktIn.ts : parserPkt.ts;

	pktOut.type = parserPkt.type;
	pktOut.write(parserPkt.data, parserPkt.length);
    pktOut.duration = 0;
    pktOut.flags = parserPkt.flags;
	pktOut.pts = pts;

    m_lastPktTime = pts;

	//CLog::debug("ps. type:%d, pts:%lld\n", parserPkt.type, parserPkt.ts);

	return true;
}

void PSRtpPackager::reset()
{
	m_parser.clear();
}

bool PSRtpPackager::getFormat(MediaFormat& fmt)
{
	fmt = m_parser.getFormat();
	return fmt.isValid();
}

void PSRtpPackager::useRtpTime()
{
	m_useRtpTime = true;
}

void PSRtpPackager::useMark(bool mark)
{
	m_useMark = mark;
}


} /* namespace av */
